package com.yaorange.certificate.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import com.yaorange.certificate.dto.UserRegisterRequest;
import com.yaorange.common.core.domain.entity.SysUser;
import com.yaorange.common.core.redis.RedisCache;
import com.yaorange.common.enums.UserRegisterStatus;
import com.yaorange.common.exception.ServiceException;
import com.yaorange.common.utils.DateUtils;
import com.yaorange.common.utils.SecurityUtils;
import com.yaorange.common.utils.SmsUtils;
import com.yaorange.common.utils.StringUtils;
import com.yaorange.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.yaorange.certificate.mapper.NjtUserRegisterMapper;
import com.yaorange.certificate.domain.NjtUserRegister;
import com.yaorange.certificate.service.INjtUserRegisterService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用户注册信息Service业务层处理
 *
 * @author loong
 * @date 2025-04-28
 */
@Slf4j
@Service
public class NjtUserRegisterServiceImpl implements INjtUserRegisterService
{
    public static final long TOURIST_ROLE = 101L;
    //    private static final Logger log = LoggerFactory.getLogger(NjtUserRegisterServiceImpl.class);
//    private static final int DELETED = 1;
//    private static final int NORMAL = 0;

    @Autowired
    private NjtUserRegisterMapper njtUserRegisterMapper;
    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 查询用户注册信息
     *
     * @param id 用户注册信息主键
     * @return 用户注册信息
     */
    @Override
    public NjtUserRegister selectNjtUserRegisterById(Long id)
    {
        return njtUserRegisterMapper.selectNjtUserRegisterById(id);
    }

    /**
     * 查询用户注册信息列表
     *
     * @param njtUserRegister 用户注册信息
     * @return 用户注册信息
     */
    @Override
    public List<NjtUserRegister> selectNjtUserRegisterList(NjtUserRegister njtUserRegister)
    {
        //列表只查询未删除的数据
        njtUserRegister.setDelFlag(Long.valueOf(UserRegisterStatus.OK.getCode()));
        return njtUserRegisterMapper.selectNjtUserRegisterList(njtUserRegister);
    }

    /**
     * 新增用户注册信息
     *
     * @param njtUserRegister 用户注册信息
     * @return 结果
     */
    @Override
    public int insertNjtUserRegister(NjtUserRegister njtUserRegister)
    {
        njtUserRegister.setCreateTime(DateUtils.getNowDate());
        return njtUserRegisterMapper.insertNjtUserRegister(njtUserRegister);
    }

    /**
     * 修改用户注册信息
     *
     * @param njtUserRegister 用户注册信息
     * @return 结果
     */
    @Override
    public int updateNjtUserRegister(NjtUserRegister njtUserRegister)
    {
        njtUserRegister.setUpdateTime(DateUtils.getNowDate());
        return njtUserRegisterMapper.updateNjtUserRegister(njtUserRegister);
    }

    /**
     * 批量删除用户注册信息
     *
     * @param ids 需要删除的用户注册信息主键
     * @return 结果
     */
    @Override
    public int deleteNjtUserRegisterByIds(Long[] ids)
    {
        for (int i = 0; i < ids.length; i++) {
            this.deleteNjtUserRegisterById(ids[i]);
        }
        return 1;
    }

    /**
     * 删除用户注册信息信息
     *
     * @param id 用户注册信息主键
     * @return 结果
     */
    @Override
    public int deleteNjtUserRegisterById(Long id)
    {
        return njtUserRegisterMapper.updateDelFlag(id, UserRegisterStatus.DELETED.getCode());
    }

    @Override
    @Transactional(readOnly = true)
    public void checkMobilePhone(String mobilePhone) {
        NjtUserRegister njtUserRegister = new NjtUserRegister();
        njtUserRegister.setMobilePhone(mobilePhone);

        List<NjtUserRegister> njtUserRegisters = njtUserRegisterMapper.selectNjtUserRegisterList(njtUserRegister);
        if (CollectionUtils.isNotEmpty(njtUserRegisters)) {
            throw new ServiceException("手机号已经存在");
        }
    }

    @Override
    public void sendValidateCode(String mobilePhone) {
        //生成6位随机数字符（只能字母字符）
        String code = StringUtils.getRandomString(6);
        //保存到redis
        stringRedisTemplate.opsForValue().set("mobilePhone:" + mobilePhone, code, 5 * 60, TimeUnit.SECONDS);
        //调用阿里云短信接口
        log.debug("给手机号:{},发送短信成功:{}",mobilePhone, code);
//        SmsUtils.sendSms(mobilePhone, code);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void register(UserRegisterRequest userRegisterRequest) {
        //校验验证码
        String code = stringRedisTemplate.opsForValue().get("mobilePhone:" + userRegisterRequest.getMobilePhone());
        if (StringUtils.isEmpty(code)) {
            throw new ServiceException("验证码无效");
        }
        if (!code.equals(userRegisterRequest.getCheckCode())) {
            throw new ServiceException("验证码错误");
        }
        //校验手机号
        checkMobilePhone(userRegisterRequest.getMobilePhone());
        //保存到Sys_user
        SysUser sysUser = new SysUser();
        sysUser.setUserName(userRegisterRequest.getMobilePhone());
        sysUser.setPassword(SecurityUtils.encryptPassword(userRegisterRequest.getPassword()));
        Date registerTime = new Date();
        sysUser.setCreateTime(registerTime);
        sysUser.setCreateBy(userRegisterRequest.getMobilePhone());
        //默认注册用户为普通用户类型
        sysUser.setUserType("02");
        sysUserService.insertUser(sysUser);
        Long userId = sysUser.getUserId();

        //设置默认角色为 游客
        sysUserService.insertUserAuth(userId, new Long[]{TOURIST_ROLE});

        //保存到user_register
        NjtUserRegister njtUserRegister = new NjtUserRegister();
        //和系统用户表使用同一个主键
        njtUserRegister.setId(userId);
        njtUserRegister.setMobilePhone(userRegisterRequest.getMobilePhone());
        njtUserRegister.setCreateTime(registerTime);
        njtUserRegister.setCreateBy(userRegisterRequest.getMobilePhone());
        njtUserRegister.setRegisterTime(registerTime);
        njtUserRegisterMapper.insertNjtUserRegister(njtUserRegister);
    }
}
